<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AppController
{
    protected $request;
    protected $appName;
	protected $app;
    protected $controller;
    protected $id;
    protected $action;

    public function __construct(Request $request)
    {
        $this->request = $request;
		$app_name = strtolower($request->route('app'));
		$this->app = get_app($app_name);
        $this->appName = Str::studly($app_name);  
        $this->controller = $this->getController();
        $this->id = $this->getId();
        $this->action = $this->getAction();
    }

    public function handle()
    {
        
		return call_user_func([$this->controller, $this->action], $this->id);
    }

    protected function getController()
    {
        $controllerName = $this->app['apiController'] ?? '';

        if (empty($controllerName) || ! class_exists($controllerName)) {
            return resolve(AppBaseController::class);
        }

        return resolve($controllerName);
    }

    protected function getId()
    {
        $id = $this->request->route('id');

        return !empty($id) ? $id : null;
    }

    protected function getAction()
    {
        switch ($this->request->method()) {
            case 'POST':
                return 'create';
                break;
            case 'DELETE':
                return 'delete';
                break;
            case 'GET':
                if ($this->id) return 'show';
                return 'index';
                break;
            case 'PUT':
                return 'update';
                break;
        }
    }

    // TODO: Automate request handling.
}
